package com.mldong.modules.sys.auth.granter;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.log.Log;
import com.mldong.auth.ILoginGranter;
import com.mldong.auth.err.AuthErrEnum;
import com.mldong.consts.CommonConstant;
import com.mldong.exception.ServiceException;
import com.mldong.modules.sys.entity.User;
import com.mldong.modules.sys.enums.AdminTypeEnum;
import com.mldong.modules.sys.service.AuthService;
import com.mldong.modules.sys.service.UserService;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Component;

/**
 * 微信小程序手机号授权登录
 * @author mldong
 * @date 2024/8/19
 */
@Component
@RequiredArgsConstructor
public class WxMaPhoneGranter implements ILoginGranter {
    private static final Log log = Log.get();
    private final UserService userService;
    @Override
    public Dict grant(Dict param) {
        String code = param.getStr("code");
        WxMaService wxMaService = SpringUtil.getBean(WxMaService.class);
        WxMaPhoneNumberInfo wxMaPhoneNumberInfo = null;
        User user = null;
        String phone = "";
        String openid = param.getStr(CommonConstant.WX_OPENID);
        String unionid = param.getStr(CommonConstant.WX_UNIONID);
        try {
            wxMaPhoneNumberInfo = wxMaService.getUserService().getPhoneNoInfo(code);
            phone = wxMaPhoneNumberInfo.getPurePhoneNumber();
            user = userService.getByPhone(phone);
        } catch (WxErrorException e) {
            log.error(e);
            ServiceException.throwBiz(AuthErrEnum.WX_AUTH_LOGIN_EX);
        }
        if(user == null) {
            user = userService.createUserByPhone(phone, AdminTypeEnum.COMMON_ADMIN.getCode(),"微信小程序手机号授权登录自动注册");
            if(user == null) {
                ServiceException.throwBiz(AuthErrEnum.NO_REG_PHONE);
            }
        }
        AuthService authService = SpringUtil.getBean(AuthService.class);
        // 自动关联openid
        if(StrUtil.isNotEmpty(openid)) {
            authService.relThirdAccount(user.getId(),CommonConstant.WX_OPENID,openid);
        }
        // 自动关联unionid
        if(StrUtil.isNotEmpty(unionid)) {
            authService.relThirdAccount(user.getId(),CommonConstant.WX_UNIONID,unionid);
        }
        return BeanUtil.toBean(user,Dict.class);
    }

}
